package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.MallWechatConfig;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.dto.WechatConfigDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.WechatConfigRepository;
import com.rockcent.service.MallWechatMenuConfigSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;

/**
 * Created by zhangjh on 2016/10/19.
 */
@RestController
public class WeChatCofigController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(WeChatCofigController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private WechatConfigRepository wechatConfigRepository;


    /**`
     * @api {get} /mall/wechat/config/info 微信配置信息
     * @apiGroup wechat
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  "data":
     *  {
     *      "id": 1,
     *      "dateCreated": "2016-10-14 19:04:16",
     *      "lastUpdated": "2016-10-14 19:04:17",
     *      "version": 5,
     *      "appid": "1111",
     *      "appSecret": "11112",
     *      "configKey": "11113",
     *      "mallId": 1,
     *      "mchid": "11111",
     *      "notifyUrl": "11111",
     *      "wechatCertificatePath": "http://uploads.rockcent.com/dev/product/face/20169/251546123108b958281-b920-49de-b57b-5433cb0c2401u=3845662385,2620759967&fm=58.jpeg",
     *      "useStatus": "YES"
     *   }
     *  }
     * */
    @RequestMapping(value = Routes.MALL_WECHAT_CONFIG_INFO, method = RequestMethod.GET)
    public JsonResult loadWeChatConfig(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            MallWechatConfig mallWechatConfig = wechatConfigRepository.findByMallId(userInfoDto.mall.getId());
            if (mallWechatConfig == null) {
                jsonResult.remind("加载微信支付配置失败",log);
                return;
            }
            jsonResult.data = mallWechatConfig;
        };
        return doing.go(request, log);
    }

    /**`
     * @api {post} /mall/wechat/config/save 微信 配置信息 保存
     * @apiGroup wechat
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} appid 应用appid
     * @apiParam {String} appSecret 应用秘钥
     * @apiParam {String} configKey 支付API密钥
     * @apiParam {String} mchid  微信支付商户号
     * @apiParam {String} notifyUrl 信息回调地址
     * @apiParam {String} wechatCertificatePath 商户微信证书
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_WECHAT_CONFIG_SAVE, method = RequestMethod.POST)
    public JsonResult saveWebChatConfig(@RequestBody WechatConfigDto wechatConfigDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (wechatConfigDto.getAppid() == null) {
                jsonResult.remind("appid 不能为空", log);
                return;
            }
            if (wechatConfigDto.getConfigKey() == null) {
                jsonResult.remind("configKey 不能为空", log);
                return;
            }
            if (wechatConfigDto.getMchid() == null) {
                jsonResult.remind("mchid 不能为空", log);
                return;
            }

            MallWechatConfig mallWechatConfig = wechatConfigRepository.findByMallId(userInfoDto.mall.getId());
            if (mallWechatConfig == null) {
                mallWechatConfig = new MallWechatConfig();
                mallWechatConfig.setUseStatus(Whether.NO);
                mallWechatConfig.setMallId(userInfoDto.mall.getId());
            }

            mallWechatConfig.setAppid(wechatConfigDto.getAppid());
            mallWechatConfig.setAppid3rd(wechatConfigDto.getAppid3rd());
            mallWechatConfig.setAppSecret3rd(wechatConfigDto.getAppSecret3rd());
            mallWechatConfig.setAppSecret(wechatConfigDto.getAppSecret());
            mallWechatConfig.setConfigKey(wechatConfigDto.getConfigKey());
            mallWechatConfig.setMchid(wechatConfigDto.getMchid());
            mallWechatConfig.setNotifyUrl(wechatConfigDto.getNotifyUrl());
            mallWechatConfig.setWechatCertificatePath(wechatConfigDto.getWechatCertificatePath());
            mallWechatConfig.setLastUpdated(new Date(System.currentTimeMillis()));
            wechatConfigRepository.saveAndFlush(mallWechatConfig);



        };

        return doing.go(request, log);
    }

    /**`
     * @api {put} /mall/wechat/config/status/update 微信配置开关
     * @apiGroup wechat
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiParam {String} useStatus <code>YES 开|NO 关</code>开关
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功",
     *  }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_WECHAT_CONFIG_STATUS_UPDATE, method = RequestMethod.PUT)
    public JsonResult updateWebChatConfigStatus(@RequestBody WechatConfigDto wechatConfigDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (StringUtils.isBlank(wechatConfigDto.getUseStatus())) {
                jsonResult.remind("useStatus 不能为空",log);
                return;
            }

            if (!EnumUtils.isValidEnum(Whether.class,wechatConfigDto.getUseStatus())) {
                jsonResult.remind("useStatus 必须为 YES / NO ",log);
                return;
            }

            MallWechatConfig mallWechatConfig = wechatConfigRepository.findByMallId(userInfoDto.mall.getId());
            if (mallWechatConfig == null) {
                jsonResult.remind("加载微信配置失败",log);
                return;
            }

            mallWechatConfig.setUseStatus(Whether.valueOf(wechatConfigDto.getUseStatus()));
            wechatConfigRepository.saveAndFlush(mallWechatConfig);
        };

        return doing.go(request, log);
    }


}
